package com.zfy.tingshu.album.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfy.tingshu.album.mapper.AlbumInfoMapper;
import com.zfy.tingshu.album.mapper.TrackInfoMapper;
import com.zfy.tingshu.album.mapper.TrackStatMapper;
import com.zfy.tingshu.album.service.AlbumInfoService;
import com.zfy.tingshu.album.service.TrackInfoService;
import com.zfy.tingshu.album.service.VodService;
import com.zfy.tingshu.common.constant.SystemConstant;
import com.zfy.tingshu.common.result.Result;
import com.zfy.tingshu.common.util.AuthContextHolder;
import com.zfy.tingshu.model.album.AlbumInfo;
import com.zfy.tingshu.model.album.TrackInfo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zfy.tingshu.model.album.TrackStat;
import com.zfy.tingshu.query.album.TrackInfoQuery;
import com.zfy.tingshu.user.client.UserInfoFeignClient;
import com.zfy.tingshu.vo.album.AlbumTrackListVo;
import com.zfy.tingshu.vo.album.TrackInfoVo;
import com.zfy.tingshu.vo.album.TrackListVo;
import com.zfy.tingshu.vo.album.TrackMediaInfoVo;
import com.zfy.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

	@Autowired
	private TrackInfoMapper trackInfoMapper;
	@Autowired
	private AlbumInfoMapper albumInfoMapper;

	@Autowired
	private AlbumInfoService albumInfoService;

	@Autowired
	private VodService vodService;

	@Autowired
	private TrackStatMapper trackStatMapper;
    @Qualifier("com.zfy.tingshu.user.client.UserInfoFeignClient")
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

	@Override
	public void findUserTrackPage(Page<TrackListVo> trackInfoPage) {
		Long userId1 = AuthContextHolder.getUserId();
		Long userId = null== userId1?1:AuthContextHolder.getUserId();

		trackInfoMapper.findUserTrackPage(trackInfoPage,userId);
	}

	@Override
	public void saveTrackInfo(TrackInfoVo trackInfoVo, Long userId) {
		try {
			//	track_info track_stat album_info;
			TrackInfo trackInfo = new TrackInfo();
			//	有相同的属性值，进行属性拷贝;
			BeanUtils.copyProperties(trackInfoVo, trackInfo);
			//	赋值用户Id
			trackInfo.setUserId(userId);
			//	order_num; 第一种查询当前专辑对应的声音集数+1; 第二种：查询专辑包含声音总数+1;
			AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfoVo.getAlbumId());
			trackInfo.setOrderNum(albumInfo.getIncludeTrackCount() + 1);
			//	处理流媒体的数据; 时长，类型这些数据页面没有传递；fileId 查询流媒体数据，然后赋值：调用云点播的api;
			TrackMediaInfoVo trackMediaInfoVo = vodService.getMediaInfo(trackInfoVo.getMediaFileId());
			//	赋值：
			trackInfo.setMediaUrl(trackMediaInfoVo.getMediaUrl());
			trackInfo.setMediaDuration(trackMediaInfoVo.getDuration());
			trackInfo.setMediaType(trackMediaInfoVo.getType());
			trackInfo.setMediaSize(trackMediaInfoVo.getSize());
			//	保存声音结束;
			trackInfoMapper.insert(trackInfo);
			//	track_stat
			saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PLAY);
			saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COLLECT);
			saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PRAISE);
			saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COMMENT);
			//	album_info; 更新数据;
			albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() + 1);
			//	更新操作;
			albumInfoMapper.updateById(albumInfo);
		} catch (BeansException e) {
			log.error("保存声音信息失败：{}", e);
			throw new RuntimeException(e);
		}
	}



	@Override
	public void removeTrackInfo(Long trackId) {
		//	查询当前声音对象;
		TrackInfo trackInfo = this.getById(trackId);
		//	track_info  track_stat album_info;
		trackInfoMapper.deleteById(trackId);
		//	track_stat
		trackStatMapper.delete(new LambdaQueryWrapper<TrackStat>().eq(TrackStat::getTrackId, trackId));
		//	album_info 更新 include_track_count
		AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfo.getAlbumId());
		//	删除一条数据；
		albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() - 1);
		//	需要更新记录;
		albumInfoMapper.updateById(albumInfo);
		//	在重新管理一下 order_num;
		//	update track_info set order_num = order_num - 1 where album_id = 1 and order_num > 52 and is_deleted = 0
		trackInfoMapper.updateOrderNum(trackInfo.getAlbumId(), trackInfo.getOrderNum());
		//	删除云点播中没有用的声音记录;
		vodService.deleteMediaFile(trackInfo.getMediaFileId());

	}

	@Override
	public void updateTrackInfo(Long trackId, TrackInfoVo trackInfoVo) {
		//	trackId + trackInfoVo 知道用户具体的修改操作了！
		//	track_info;
		TrackInfo trackInfo = this.getById(trackId);
		//	先获取原始的文件Id
		String originMediaFileId = trackInfo.getMediaFileId();
		//	属性赋值：
		BeanUtils.copyProperties(trackInfoVo, trackInfo);
		//	判断声音是否被修改;
		if (!originMediaFileId.equals(trackInfoVo.getMediaFileId())) {
			//	修改了声音;
			TrackMediaInfoVo mediaInfo = vodService.getMediaInfo(trackInfoVo.getMediaFileId());
			//	赋值最新流媒体数据;
			trackInfo.setMediaType(mediaInfo.getType());
			trackInfo.setMediaDuration(mediaInfo.getDuration());
			trackInfo.setMediaSize(mediaInfo.getSize());
			trackInfo.setMediaFileId(trackInfoVo.getMediaFileId());
			//	原有不要的话;
			vodService.deleteMediaFile(originMediaFileId);
		}
		//	更新数据;
		this.updateById(trackInfo);
	}

	@Override
	public void findAlbumTrackPage(Page<AlbumTrackListVo> albumTrackListVoPage, Long albumId, Long userId) {
		/*
            1.  需要先根据专辑Id获取到声音列表;
            2.  判断用户是否登录：
                    null != userId;

                    null == userId;
                2.1 判断专辑类型;
                2.2 除用户已购买的声音Id；
         */
		IPage<AlbumTrackListVo> albumTrackListVoIPage = trackInfoMapper.selectAlbumTrackList(albumTrackListVoPage,albumId);
		//查询专辑类型
		AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
		//判断用户是否登录
		if (null==userId){
			//没有登录；专辑类型是付费时，除免费试听都需要付费
			if (!SystemConstant.ALBUM_PAY_TYPE_FREE.equals(albumInfo.getPayType())){
				//免费试听集数:5
				Integer tracksForFree = albumInfo.getTracksForFree();
				//除免费试听声音都需要付费
				albumTrackListVoIPage.getRecords().stream().filter(albumTrackListVo -> albumTrackListVo.getOrderNum()>tracksForFree).forEach(albumTrackListVo -> {
					albumTrackListVo.setIsShowPaidMark(true);
				});
			}
		}else {
			//获取用户信息
			Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfo(userId);
			Assert.notNull(userInfoVoResult,"查询用户信息失败");
			UserInfoVo userInfoVo = userInfoVoResult.getData();
			Assert.notNull(userInfoVo,"查询用户信息失败");
			//什么一个变量；记录是否需要付费；false：免费；true：付费
			boolean isPaid = false;
			//判断专辑的类型：vip 免费
			if (SystemConstant.ALBUM_PAY_TYPE_VIPFREE.equals(albumInfo.getPayType())){
				//前提 用户是vip 且已过期
				if ((userInfoVo.getIsVip()==1&&userInfoVo.getVipExpireTime().before(new Date()))||userInfoVo.getIsVip()==0){
					//需要付费
					isPaid=true;
				}
			}else if (SystemConstant.ALBUM_PAY_TYPE_REQUIRE.equals(albumInfo.getPayType())){
				//必须付费
				isPaid = true;
			}
			//判断需要付费的情况
			if (isPaid){
				//远程调用，需要知道用户购买了哪些声音；专辑Id；付费声音列表；userId--从本地线程中获取；
				List<AlbumTrackListVo> trackListVos = albumTrackListVoIPage.getRecords().stream().filter(albumTrackListVo -> {
					return albumTrackListVo.getOrderNum() > albumInfo.getTracksForFree();
				}).collect(Collectors.toList());
				//获取用户购买的声音列表如果用户购买了；将购买的声音Id与状态存储到map集合中；map.put(trackId,1)-买过；map.put(trackId,id)-未买过

				Result<Map<Long,Integer>> mapResult= userInfoFeignClient.userIsPaidTrack(albumId,trackListVos);
				Assert.notNull(mapResult,"查询用户购买声音失败");
				Map<Long, Integer> map = mapResult.getData();
//				map.put(trackId,1)-买过 map.put(trackId,0)-没买过;
				trackListVos.forEach(albumTrackListVo -> albumTrackListVo.setIsShowPaidMark(map.get(albumTrackListVo.getTrackId())==0));
			}
		}

	}

    @Override
    public void updateStat(Long albumId, Long trackId, String statType, Integer count) {
        //更新声音播放量
		trackInfoMapper.updateStat(trackId,statType,count);
		//	更新专辑播放量
		if (statType.equals(SystemConstant.TRACK_STAT_PLAY)){
			albumInfoService.updateStat(albumId,SystemConstant.ALBUM_STAT_PLAY,count);
		}

    }

    public void saveTrackStat(Long trackId, String statPlay) {
		TrackStat trackStat = new TrackStat();
		//	赋值
		trackStat.setTrackId(trackId);
		trackStat.setStatType(statPlay);
		trackStat.setStatNum(new Random().nextInt(1000));
		//	数据保存
		trackStatMapper.insert(trackStat);
	}
}
